package com.tj.collection.controller.lending;

import com.alibaba.fastjson.JSON;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.EntityUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Lists;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.tj.collection.aop.anno.CheckProductCategory;
import com.tj.collection.aop.anno.ClickOnce;
import com.tj.collection.bean.ApiResponse;
import com.tj.collection.bean.ModuleResponse;
import com.tj.collection.bean.RedisKey;
import com.tj.collection.bean.RequestBasicInfo;
import com.tj.collection.common.RequestLocalInfo;
import com.tj.collection.controller.lending.request.ClManualAllocationRequest;
import com.tj.collection.controller.lending.request.ClOrderQueryRequest;
import com.tj.collection.controller.lending.request.ClQueryRequest;
import com.tj.collection.controller.lending.request.CollectionMoveRequest;
import com.tj.collection.controller.lending.response.*;
import com.tj.collection.db.dao.*;
import com.tj.collection.db.domain.Role;
import com.tj.collection.db.entity.ClImagesEntity;
import com.tj.collection.db.entity.ClMerchantEntity;
import com.tj.collection.db.entity.ClReceiverEntity;
import com.tj.collection.db.entity.ClStageEntity;
import com.tj.collection.db.entity.business.ClAllocationInfoEntity;
import com.tj.collection.db.entity.business.ClCountInfoEntity;
import com.tj.collection.db.entity.business.ClOrderAllocationEntity;
import com.tj.collection.db.enums.RoleKeyEnum;
import com.tj.collection.db.service.AdminRoleService;
import com.tj.collection.enums.ClActiveStatusEnum;
import com.tj.collection.enums.CollectionOverdueTimeEnums;
import com.tj.collection.enums.ExtensionStatusEnum;
import com.tj.collection.enums.ReceiverStatusEnum;
import com.tj.collection.service.AllocationService;
import com.tj.collection.service.param.ClOrderSearchConditions;
import com.tj.collection.service.param.ClSearchConditions;
import com.tj.collection.utils.CalculatorUtils;
import com.tj.collection.utils.ConfigUtil;
import com.tj.collection.utils.HttpUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2019/9/10
 * Time: 下午2:48
 */
@RestController
@RequestMapping("/collection/v2")
public class ClAllocationController {

    public static final Log LOGGER = LogFactory.getLog(ClAllocationController.class);

    @Autowired
    private ConfigUtil configUtil;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private AllocationService allocationService;
    @Autowired
    private AdminRoleService adminRoleService;
    @Autowired
    private ClStageDao clStageDao;
    @Autowired
    private ClAllocationDetailDao clAllocationDetailDao;
    @Autowired
    private MerchantCodeMapDao merchantCodeMapDao;
    @Autowired
    private ClMerchantDao clMerchantDao;

    @Autowired
    private ClReceiverDao clReceiverDao;

    private static Map<String, Object> dataMap = new ConcurrentHashMap<>();

    @Autowired
    private ClImagesDao imagesDao;


    @ClickOnce
    @CheckProductCategory
    @RequestMapping("/payLink/{orderNo}")
    public ModuleResponse<ClRepaymentLinkResponse> payLink(@PathVariable String orderNo) {
        try {
            String res = HttpUtil.getPage("http://147.139.66.58:9101/order/repay/link?collectionNo=" + orderNo);
            LOGGER.info("== pay url请求结果 ==,res:{}",res);
            Any deserialize = JsonIterator.deserialize(res);
            return new ModuleResponse<>(new ClRepaymentLinkResponse(deserialize.get("data").toString(), deserialize.get("data").toString()));
        } catch (Exception e) {
            return new ModuleResponse<>(new ClRepaymentLinkResponse("fail to create link!!", "fail to reNew link!!"));
        }
    }
    @ClickOnce
    @CheckProductCategory
    @RequestMapping("/extentionLink/{orderNo}")
    public ModuleResponse<ClRepaymentLinkResponse> extentionLink(@PathVariable String orderNo) {
        try {
            String res = HttpUtil.getPage("http://147.139.66.58:9101/order/extention/repay/link?collectionNo=" + orderNo);
            LOGGER.info("== 展期url请求结果 ==,res:{}",res);
            Any deserialize = JsonIterator.deserialize(res);
            return new ModuleResponse<>(new ClRepaymentLinkResponse(deserialize.get("data").toString(), deserialize.get("data").toString()));
        } catch (Exception e) {
            return new ModuleResponse<>(new ClRepaymentLinkResponse("fail to create link!!", "fail to reNew link!!"));
        }
    }

    @ClickOnce
    @CheckProductCategory
    @RequestMapping("/images/{collectionNo}")
    public ModuleResponse<ClImagesResponse> getImages(@PathVariable String collectionNo) {
        if (StringUtils.isEmpty(collectionNo)) {
            throw new ApplicationException(" collectionNo is empty");
        }
        try {
            ClImagesEntity clImagesEntity = imagesDao.selectByCollectionNo(collectionNo);
            if (clImagesEntity == null) {
                return new ModuleResponse<>(new ClImagesResponse(""));
            }
            return new ModuleResponse<>(new ClImagesResponse(clImagesEntity.getImagesJson()));
        } catch (Exception e) {
            throw new ApplicationException("fetch images failed");
        }
    }

    /**
     * 案件列表
     *
     * @param clQueryRequest
     * @param page
     * @return
     */
    @ClickOnce
    @CheckProductCategory
    @RequestMapping("/distributeOrderGet/list")
    public ModuleResponse<ClQueryResponse> collectionDistributeGet(@RequestBody ClQueryRequest clQueryRequest, Page page) {
        try {
            if (page == null) {
                page = new Page(100);
            }
            Integer adminId = RequestLocalInfo.getCurrentAdmin().getId().intValue();
            String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
            RequestBasicInfo requestBasicInfo = RequestLocalInfo.getRequestBasicInfo();

            List<String> pcList = null;
            if ("android".equals(requestBasicInfo.getAppClient()) && StringUtils.isNotEmpty(requestBasicInfo.getPackageName())) {
                pcList = getProductCategoryListByPackageName(requestBasicInfo.getPackageName());
                LOGGER.info("getMerchantCodeByPackageName,6666,{}", JSON.toJSONString(pcList));
            }

            ClSearchConditions clSearchConditions = this.getClSearchConditions(clQueryRequest, merchantCode, pcList, adminId);
            long time = System.currentTimeMillis();
            LOGGER.info("1111111111");
            List<ClAllocationInfoEntity> clAllocationInfoEntityList = allocationService.getCollectionAgentAllocationList(clSearchConditions, page, false);
            LOGGER.info("33333333,cost:{},size:{}", (System.currentTimeMillis() - time), clAllocationInfoEntityList.size());
            time = System.currentTimeMillis();
            ClCountInfoEntity clCountInfoEntity = null;
            if ("web".equals(requestBasicInfo.getAppClient())) {
                clCountInfoEntity = clAllocationDetailDao.selectAgentWorkStats(adminId, DateUtil.getDate(clQueryRequest.getStartDate(), "yyyy-MM-dd"), DateUtil.getDate(clQueryRequest.getEndDate(), "yyyy-MM-dd"));
            }
            LOGGER.info("4444444444,cost:{},totalCount:{}", (System.currentTimeMillis() - time), clCountInfoEntity.getTotalCount());
            time = System.currentTimeMillis();
            //增量信息查询
            List<ClMerchantEntity> clMerchantEntityList = clMerchantDao.selectAllClMerchantList();
            LOGGER.info("55555555555,time:{},size:{}", (System.currentTimeMillis() - time), clMerchantEntityList.size());

            List<String> collectionNos = clAllocationInfoEntityList.parallelStream().map(ClAllocationInfoEntity::getCollectionNo).collect(Collectors.toList());
            List<ClReceiverEntity> clReceiverEntities = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(collectionNos)) {
                clReceiverEntities = clReceiverDao.selectByCollectionNos(collectionNos);
            }

            LOGGER.info("666666,time:{},size:{},page:{}", (System.currentTimeMillis() - time), collectionNos.size(), JsonStream.serialize(page));
            return new ModuleResponse<>(new ClQueryResponse(clAllocationInfoEntityList, clCountInfoEntity, clMerchantEntityList, clReceiverEntities), page);
        } catch (Exception e) {
            return new ModuleResponse<>();
        }
    }

    private List<String> getProductCategoryListByPackageName(String packageName) {
        //TODO 新增产品类目后需要修改
        if ("in.dhanadhan.loan.money.cash".equals(packageName)) {
            return Lists.newArrayList("dhanaDhanV6All", "dhanaDhanV7All");
        } else if ("com.vayloan.app".equals(packageName)) {
            return Lists.newArrayList("loanZoneAll");
        } else if ("in.cashzone.app".equals(packageName)) {
            return Lists.newArrayList("cashZoneAll");
        } else {
            return null;
        }
    }

    /**
     * 案件列表
     *
     * @param clQueryRequest
     * @param page
     * @return
     */
    @CheckProductCategory
    @RequestMapping("/distributeOrderGet/list/export")
    public ModuleResponse<ClQueryExpResponse> collectionDistributeGetExport(@RequestBody ClQueryRequest clQueryRequest, Page page) {
        if (!configUtil.getCollectionExportAllow()) {
            throw new ApplicationException("System exception");
        }

        Integer adminId = RequestLocalInfo.getCurrentAdmin().getId().intValue();
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        ClSearchConditions clSearchConditions = this.getClSearchConditions(clQueryRequest, merchantCode, null, adminId);
        List<ClAllocationInfoEntity> clAllocationInfoEntityList = allocationService.getCollectionAgentAllocationList(clSearchConditions, page, false);
        List<ClMerchantEntity> clMerchantEntityList = clMerchantDao.selectAllClMerchantList();
        return new ModuleResponse<>(new ClQueryExpResponse(clAllocationInfoEntityList, clMerchantEntityList), page);
    }

    private ClSearchConditions getClSearchConditions(ClQueryRequest clQueryRequest, String merchantCode, List<String> pcList, Integer adminId) {
        ClSearchConditions clSearchConditions = new ClSearchConditions();
        clSearchConditions.setMerchantCode(merchantCode);
        clSearchConditions.setProductCategoryList(CollectionUtils.isNotEmpty(pcList) ? pcList : null);
        clSearchConditions.setAdminId(adminId);
        clSearchConditions.setReceiverStatus(ReceiverStatusEnum.ALLOCATE_SUCCESS.getStatus());
        //权限管理员
        if (this.hasAllCollectPermission()) {
            LOGGER.info("== 拥有管理员权限==");
            clSearchConditions.setAdminId(null);
        } else {
            LOGGER.info("== 没有管理员权限==");
            clSearchConditions.setAdminId(adminId);
        }
        if (StringUtils.isNotEmpty(clQueryRequest.getWorkTaskStatus())) {
            clSearchConditions.setWorkTaskStatus(clQueryRequest.getWorkTaskStatus());
            if ("doing".equals(clQueryRequest.getWorkTaskStatus())) {
                clSearchConditions.setWorkTaskStatus("doing");
                clSearchConditions.setExtensionStatus(ExtensionStatusEnum.UN_EXTENSION.getStatus());
            }
            if ("extension".equals(clQueryRequest.getWorkTaskStatus())) {
                clSearchConditions.setWorkTaskStatus("doing");
                clSearchConditions.setExtensionStatus(ExtensionStatusEnum.WAITING_EXTENSION_REPAY.getStatus());
            }
        }

        if (StringUtils.isNotEmpty(clQueryRequest.getStartDate())) {
            clSearchConditions.setStartDate(clQueryRequest.getStartDate());
        } else {
            clSearchConditions.setStartDate(DateUtil.getDate(new Date()));
        }
        if (StringUtils.isNotEmpty(clQueryRequest.getEndDate())) {
            clSearchConditions.setEndDate(clQueryRequest.getEndDate());
        } else {
            clSearchConditions.setEndDate(DateUtil.getDate(new Date()));
        }
        if (clQueryRequest.getIsNewAdd() != null) {
            if (clQueryRequest.getIsNewAdd() == 0) {
                clSearchConditions.setBorrowType(1);
            }
            if (clQueryRequest.getIsNewAdd() == 1) {
                clSearchConditions.setBorrowType(2);
            }
        }
        if (StringUtils.isNotEmpty(clQueryRequest.getName())) {
            clSearchConditions.setName(clQueryRequest.getName());
        }
        if (StringUtils.isNotEmpty(clQueryRequest.getMobile())) {
            clSearchConditions.setMobile(clQueryRequest.getMobile());
        }
        if (StringUtils.isNotEmpty(clQueryRequest.getIdentityNo())) {
            clSearchConditions.setIdentityNo(clQueryRequest.getMobile());
        }
        if (configUtil.getCommonTypeQuerySwitch()) {
            if (clQueryRequest.getCollectionStatus() != null) {
                clSearchConditions.setCommentType(clQueryRequest.getCollectionStatus());
            }
        }
        if (clQueryRequest.getOverdueTime() != null) {
            CollectionOverdueTimeEnums timeEnums = CollectionOverdueTimeEnums.getEnum(clQueryRequest.getOverdueTime());
            if (null == timeEnums) {
                clSearchConditions.setStartOverdueDays(null);
                clSearchConditions.setEndOverdueDays(null);
            }
            clSearchConditions.setStartOverdueDays(timeEnums.getStart());
            clSearchConditions.setEndOverdueDays(timeEnums.getEnd());
        }
        if (clQueryRequest.getOverdueDays() != null && clQueryRequest.getOverdueDays().intValue() >= -3) {
            clSearchConditions.setStartOverdueDays(clQueryRequest.getOverdueDays());
            clSearchConditions.setEndOverdueDays(clQueryRequest.getOverdueDays());
        }
        if (clQueryRequest.getCollectionType() != null) {
            clSearchConditions.setCollectionType(clQueryRequest.getCollectionType());
        }
        if (clQueryRequest.getSort() != null && StringUtils.isNotEmpty(clQueryRequest.getSortType())) {
            clSearchConditions.setSort(clQueryRequest.getSort());
            if (this.determineChar(clQueryRequest.getSortType())) {
                throw new ApplicationException("模板参数未通过校验");
            }
            clSearchConditions.setSortType(clQueryRequest.getSortType());
        }
        if (CollectionUtils.isNotEmpty(clQueryRequest.getUserLanguageList())) {
            clSearchConditions.setUserLanguageList(clQueryRequest.getUserLanguageList());
        }
        if (StringUtils.isNotEmpty(clQueryRequest.getTradeNo())) {
            clSearchConditions.setOrderNo(clQueryRequest.getTradeNo());
        }
        if (clQueryRequest.getActiveType() != null) {
            ClActiveStatusEnum clActiveStatusEnum = ClActiveStatusEnum.getEnum(clQueryRequest.getActiveType());
            if (clActiveStatusEnum != null) {
                Date date = new Date();
                clSearchConditions.setActiveStartDate(DateUtil.getDate(DateUtil.addDate(date, -1 * clActiveStatusEnum.getDays()), "yyyy-MM-dd HH:mm:ss"));
                clSearchConditions.setActiveEndDate(DateUtil.getDate(date, "yyyy-MM-dd HH:mm:ss"));
            }
        }
        return clSearchConditions;
    }

    /**
     * 防SQL注入
     *
     * @param str
     * @return
     */
    private Boolean determineChar(String str) {
        String reg = "@@|==|--|!|;|\\!|"
                + "\\s(union|and|or|where|exec|like|from|trancate|char|substr|ascii|count|into)\\s|" +
                "\\b(select|update|delete|insert|trancate|char|alter|substr|ascii|declare|exec|drop)\\s";
        Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);//不区分大小写
        if (pattern.matcher(str).find()) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否是催收主管或者更高级的权限（用来控制展示员工下拉列表）
     *
     * @return
     */
    private boolean hasAllCollectPermission() {
        LOGGER.info("hasAllCollectPermission", RequestLocalInfo.getCurrentAdmin().getId());
        List<Role> roleList = adminRoleService.getRolesByAdminId(RequestLocalInfo.getCurrentAdmin().getId());
        List<RoleKeyEnum> roleKeyEnumList = RoleKeyEnum.getCollectionAllPermissionEnum();
        for (RoleKeyEnum roleKeyEnum : roleKeyEnumList) {
            for (Role role : roleList) {
                if (roleKeyEnum.getType().equals(role.getRoleKey())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 逾期列表
     *
     * @param clOrderQueryRequest
     * @param page
     * @return
     */
    @ClickOnce
    @CheckProductCategory
    @RequestMapping("/overdueOrderGet/list")
    public ModuleResponse<ClOrderQueryResponse> collectionOrderOverdueGet(@RequestBody ClOrderQueryRequest clOrderQueryRequest, Page page) {
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        List<ClOrderAllocationEntity> clOrderAllocationEntityList = allocationService.getCollectionOrderList(this.convertOrderSearchConditions(clOrderQueryRequest), page);
        List<ClMerchantEntity> clMerchantEntityList = clMerchantDao.selectAllClMerchantList();
        return new ModuleResponse<>(new ClOrderQueryResponse(clOrderAllocationEntityList, clMerchantEntityList), page);
    }

    /**
     * 逾期列表 -导出
     *
     * @param clOrderQueryRequest
     * @param page
     * @return
     */
    @CheckProductCategory
    @RequestMapping("/overdueOrderGet/list/export")
    public ModuleResponse<ClOrderQueryExpResponse> collectionOrderOverdueGetExportV2(@RequestBody ClOrderQueryRequest clOrderQueryRequest, Page page) {
        LOGGER.info("逾期数据导出,admin:{},clOrderQueryRequest:{}", JSON.toJSONString(RequestLocalInfo.getCurrentAdmin()), JSON.toJSONString(clOrderQueryRequest));
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        String productType = RequestLocalInfo.getCurrentAdmin().getProductCategory();
        List<ClOrderAllocationEntity> clOrderAllocationEntityList = allocationService.getCollectionOrderList(this.convertOrderSearchConditions(clOrderQueryRequest), page);
        List<ClStageEntity> clStageEntityList = clStageDao.getStagesByMerchantCode(merchantCode);
        List<ClMerchantEntity> clMerchantEntityList = clMerchantDao.selectAllClMerchantList();
        return new ModuleResponse<>(new ClOrderQueryExpResponse(clOrderAllocationEntityList, clStageEntityList, clMerchantEntityList), page);
    }

    /**
     * 逾期列表 -导出
     *
     * @param response
     * @param clOrderQueryRequest
     * @return
     */
    @CheckProductCategory
    @RequestMapping("/overdueOrderGet/export")
    public ApiResponse collectionOrderOverdueGetExport(HttpServletResponse response, @RequestBody ClOrderQueryRequest clOrderQueryRequest) {
        LOGGER.info("逾期数据导出,admin:{},clOrderQueryRequest:{}", JSON.toJSONString(RequestLocalInfo.getCurrentAdmin()), JSON.toJSONString(clOrderQueryRequest));
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        String productType = RequestLocalInfo.getCurrentAdmin().getProductCategory();
        List<ClOrderAllocationEntity> clOrderAllocationEntityList = allocationService.getCollectionOrderList(this.convertOrderSearchConditions(clOrderQueryRequest), new Page(50000));
        List<ClStageEntity> clStageEntityList = clStageDao.getStagesByMerchantCode(merchantCode);
        Map<String, ClStageEntity> clStageEntityMap = EntityUtils.makeEntityMap(clStageEntityList, "stageCode");
        if (clOrderAllocationEntityList.size() > 0) {
            try {
                Workbook workbook = new HSSFWorkbook();
                Sheet sheet = workbook.createSheet("Export Data List");
                Row firstRow = sheet.createRow(0);
                firstRow.createCell(0).setCellValue("Merchant(Product)");
                firstRow.createCell(1).setCellValue("Loan Id");
                firstRow.createCell(2).setCellValue("Customer Name");
                firstRow.createCell(3).setCellValue("Mobile Number");
                firstRow.createCell(4).setCellValue("Loan Amount");
                firstRow.createCell(5).setCellValue("Due Amount");
                firstRow.createCell(6).setCellValue("Total Amount");
                firstRow.createCell(7).setCellValue("DPD days");
                firstRow.createCell(8).setCellValue("Bucket");
                firstRow.createCell(9).setCellValue("Agent Name");
                firstRow.createCell(10).setCellValue("Language");

                for (int i = 0; i < clOrderAllocationEntityList.size(); i++) {
                    ClOrderAllocationEntity clOrderAllocationEntity = clOrderAllocationEntityList.get(i);

                    BigDecimal expireAmount = new BigDecimal(0);//应还总金额
                    BigDecimal noRepayAmount = new BigDecimal(0);//待还款金额
                    BigDecimal lateFee = new BigDecimal(0);//总罚息
                    if (clOrderAllocationEntity.getOverdueDays() > 0) {
                        BigDecimal overdueFee = CalculatorUtils.calculateOverdueFee(clOrderAllocationEntity.getBorrowCapital(),
                                clOrderAllocationEntity.getLateFeeRatio(),
                                clOrderAllocationEntity.getOverdueDays());
                        lateFee = overdueFee.add(clOrderAllocationEntity.getLateServiceFee());
                        expireAmount = CalculatorUtils.repaymentTotalCapital(clOrderAllocationEntity.getBorrowCapital(), clOrderAllocationEntity.getInterest(),
                                overdueFee, clOrderAllocationEntity.getLateServiceFee());
                        noRepayAmount = expireAmount.subtract(clOrderAllocationEntity.getPaidAmount());
                    } else {
                        lateFee = new BigDecimal(0);
                        expireAmount = CalculatorUtils.repaymentTotalCapital(clOrderAllocationEntity.getBorrowCapital(), clOrderAllocationEntity.getInterest(),
                                BigDecimal.ZERO, BigDecimal.ZERO);
                        noRepayAmount = expireAmount.subtract(clOrderAllocationEntity.getPaidAmount());
                    }
                    expireAmount = expireAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
                    noRepayAmount = noRepayAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
                    lateFee = lateFee.setScale(2, BigDecimal.ROUND_HALF_UP);

                    Row row = sheet.createRow(i + 1);
                    row.createCell(0).setCellValue(clOrderAllocationEntity.getSourceMerchantCode());
                    row.createCell(1).setCellValue(clOrderAllocationEntity.getOrderNo());
                    row.createCell(2).setCellValue(clOrderAllocationEntity.getName());
                    row.createCell(3).setCellValue(clOrderAllocationEntity.getMobile());
                    row.createCell(4).setCellValue(clOrderAllocationEntity.getBorrowCapital().setScale(2).toString());
                    row.createCell(5).setCellValue(lateFee.setScale(2).toString());
                    row.createCell(6).setCellValue(expireAmount.setScale(2).toString());
                    row.createCell(7).setCellValue(clOrderAllocationEntity.getOverdueDays());
                    ClStageEntity clStageEntity = clStageEntityMap.get(clOrderAllocationEntity.getStageCode());
                    row.createCell(8).setCellValue(clStageEntity != null ? clStageEntity.getStageName() : clOrderAllocationEntity.getStageCode());
                    row.createCell(9).setCellValue(clOrderAllocationEntity.getAgentName());
                    row.createCell(10).setCellValue(clOrderAllocationEntity.getUserLanguage());
                }
                OutputStream out = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String currentDate = sdf.format(new Date());
                String excelName = "data";
                try {
                    out = response.getOutputStream();
                    response.setContentType("application/ms-excel;charset=UTF-8");
                    response.setHeader("Content-Disposition", "attachment;filename="
                            .concat(String.valueOf(URLEncoder.encode(currentDate + excelName + ".xls", "UTF-8"))));
                    workbook.write(out);
                } catch (IOException e) {
                    LOGGER.error("输出流错误{}", e);
                } finally {
                    out.close();
                }
            } catch (IOException e) {
                LOGGER.error("导出失败{}", e);
            }
        }
        return new ApiResponse();
    }

    private ClOrderSearchConditions convertOrderSearchConditions(ClOrderQueryRequest clOrderQueryRequest) {
        String merchantCode = RequestLocalInfo.getCurrentAdmin().getMerchantCode();
        String productType = RequestLocalInfo.getCurrentAdmin().getProductCategory();

        ClOrderSearchConditions clOrderSearchConditions = new ClOrderSearchConditions();
        clOrderSearchConditions.setMerchantCode(merchantCode);
        if (clOrderQueryRequest.getAppName() != null) {
            clOrderSearchConditions.setAppName(clOrderQueryRequest.getAppName());
        }
//        clOrderSearchConditions.setProductType(productType);
        if (clOrderQueryRequest.getOverdueTime() != null) {
            CollectionOverdueTimeEnums timeEnums = CollectionOverdueTimeEnums.getEnum(clOrderQueryRequest.getOverdueTime());
            if (timeEnums != null) {
                clOrderSearchConditions.setStartOverdueDays(timeEnums.getStart());
                clOrderSearchConditions.setEndOverdueDays(timeEnums.getEnd());
            }
        }
        if (clOrderQueryRequest.getOverdueDays() != null && clOrderQueryRequest.getOverdueDays().intValue() >= -3) {
            clOrderSearchConditions.setStartOverdueDays(clOrderQueryRequest.getOverdueDays());
            clOrderSearchConditions.setEndOverdueDays(clOrderQueryRequest.getOverdueDays());
        }
        if (clOrderQueryRequest.getIsNewAdd() != null) {
            if (clOrderQueryRequest.getIsNewAdd() == 0) {
                clOrderSearchConditions.setBorrowType(1);
            }
            if (clOrderQueryRequest.getIsNewAdd() == 1) {
                clOrderSearchConditions.setBorrowType(2);
            }
        }
        if (clOrderQueryRequest.getIsAllocation() != null) {
            clOrderSearchConditions.setIsAllocation(clOrderQueryRequest.getIsAllocation());
        }
        if (StringUtils.isNotEmpty(clOrderQueryRequest.getChannel())) {
            clOrderSearchConditions.setChannel(clOrderQueryRequest.getChannel());
        }
        if (StringUtils.isNotEmpty(clOrderQueryRequest.getName())) {
            clOrderSearchConditions.setName(clOrderQueryRequest.getName());
        }
        if (StringUtils.isNotEmpty(clOrderQueryRequest.getMobile())) {
            clOrderSearchConditions.setMobile(clOrderQueryRequest.getMobile());
        }
        if (clOrderQueryRequest.getProcessingStatus() != null) {
            clOrderSearchConditions.setProcessingStatus(clOrderQueryRequest.getProcessingStatus());
        }
        if (clOrderQueryRequest.getFollowId() != null) {
            clOrderSearchConditions.setAdminId(clOrderQueryRequest.getFollowId());
        }
        if (StringUtils.isNotEmpty(clOrderQueryRequest.getUserLanguage())) {
            clOrderSearchConditions.setUserLanguage(clOrderQueryRequest.getUserLanguage());
        }
        if (clOrderQueryRequest.getCollectionStatus() != null) {
            clOrderSearchConditions.setCollectionStatus(clOrderQueryRequest.getCollectionStatus());
        }
        return clOrderSearchConditions;
    }

    /**
     * 手动分单
     *
     * @param clManualAllocationRequest
     * @return
     */
    @ClickOnce
    @CheckProductCategory
    @RequestMapping("/order/distribute")
    public ApiResponse distributeCollectionOrder(@RequestBody ClManualAllocationRequest clManualAllocationRequest) {
//        if (redisClient.get(RedisKey.COLLECTION_ALLOCATION_DAILY_KEY, DateUtil.getDate(new Date())) == null) {
//            throw new ApplicationException("Wait for overdue data refresh");
//        }
        String name = RequestLocalInfo.getCurrentAdmin().getName();

        List<String> tradeNos = clManualAllocationRequest.getTradeNos();
        //分单
        allocationService.manualAllocation(tradeNos, clManualAllocationRequest.getFollowId(), name);
        return new ApiResponse<>();
    }

    /**
     * 手动分单
     *
     * @param collectionMoveRequest
     * @return
     */
    @CheckProductCategory
    @RequestMapping("/order/transfer")
    public ApiResponse distributeCollectionOrder(@RequestBody CollectionMoveRequest collectionMoveRequest) {
        allocationService.updateLanguage(collectionMoveRequest.getCollectionNo(), collectionMoveRequest.getUserLanguage());
        return new ApiResponse<>();
    }


}
